import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Popconfirm } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import { getAllCleaningRecords, createCleaningRecord, updateCleaningRecord, getCleaningRecordById ,getAllCleaners, deleteCleaningRecord} from '../../../services/cleaning';
import { getStores,getVenues} from '../../../services/store';

const { RangePicker } = DatePicker;
const { Option } = Select;

const statusMap = {
  0: { text: '待处理', color: 'gold' },
  1: { text: '进行中', color: 'blue' },
  2: { text: '已完成', color: 'green' },
  3: { text: '已取消', color: 'red' },
};

const CleaningRecordList = () => {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [recordForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [formTitle, setFormTitle] = useState('创建保洁记录');
  const [stores, setStores] = useState([]);
  const [cleaners, setCleaners] = useState([]);
  const [venues, setVenues] = useState([]);

  const fetchRecords = async () => {
    try {
      setLoading(true);
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      };
      const res = await getAllCleaningRecords(params);
      if (res.success) {
        setRecords(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total || 0,
        });
      } else {
        message.error(res.message || '获取保洁记录列表失败');
      }
    } catch (error) {
      message.error('获取保洁记录列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const fetchDropdownData = async () => {
      try {
        const storesRes = await getStores({ page: 1, pageSize: 999 });
        if (storesRes.success) {
          setStores(storesRes.data.list || []);
        } else {
          message.error(storesRes.message || '获取门店列表失败');
        }

        const cleanersRes = await getAllCleaners({ page: 1, pageSize: 999 });
        if (cleanersRes.success) {
          setCleaners(cleanersRes.data.list || []);
        } else {
          message.error(cleanersRes.message || '获取保洁员列表失败');
        }

        const venuesRes = await getVenues({ page: 1, pageSize: 999 });
        if (venuesRes.success) {
          setVenues(venuesRes.data.list || []);
        } else {
          message.error(venuesRes.message || '获取场地列表失败');
        }
      } catch (error) {
        message.error('获取下拉列表数据失败');
      }
    };

    fetchDropdownData();
  }, []);

  useEffect(() => {
    fetchRecords();
  }, [pagination.current, pagination.pageSize, searchParams]);

  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await getCleaningRecordById(record.id);
      if (res.success) {
        setCurrentRecord(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取保洁记录详情失败');
      }
    } catch (error) {
      message.error('获取保洁记录详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setFormTitle('创建保洁记录');
    setCurrentRecord(null);
    recordForm.resetFields();
    setFormVisible(true);
  };

  const handleEdit = (record) => {
    setCurrentRecord(record);
    setFormTitle('编辑保洁记录');
    recordForm.setFieldsValue({
      ...record,
      start_time: record.start_time ? moment(record.start_time) : null,
      end_time: record.end_time ? moment(record.end_time) : null,
    });
    setFormVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteCleaningRecord(id);
      if (res.success) {
        message.success('删除成功');
        fetchRecords();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  const handleFormSubmit = async () => {
    try {
      const values = await recordForm.validateFields();
      setLoading(true);
      const submitValues = {
        ...values,
        start_time: values.start_time ? values.start_time.toISOString() : null,
        end_time: values.end_time ? values.end_time.toISOString() : null,
      };

      let res;
      if (currentRecord) {
        res = await updateCleaningRecord(currentRecord.id, submitValues);
      } else {
        res = await createCleaningRecord(submitValues);
      }

      if (res.success) {
        message.success(`${currentRecord ? '更新' : '创建'}成功`);
        setFormVisible(false);
        fetchRecords();
      } else {
        message.error(res.message || `${currentRecord ? '更新' : '创建'}失败`);
      }
    } catch (error) {
      message.error('表单提交失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '门店名称',
      dataIndex: ['store', 'name'],
      key: 'store_name',
    },
    {
      title: '场地名称',
      dataIndex: ['venue', 'name'],
      key: 'venue_name',
    },
    {
      title: '保洁人员',
      dataIndex: ['cleaner', 'name'],
      key: 'cleaner_name',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        return <Tag color={statusMap[status]?.color}>{statusMap[status]?.text}</Tag>;
      },
    },
    { title: '开始时间', dataIndex: 'start_time', key: 'start_time', render: (text) => moment(text).format('YYYY-MM-DD HH:mm') },
    { title: '结束时间', dataIndex: 'end_time', key: 'end_time', render: (text) => moment(text).format('YYYY-MM-DD HH:mm') },
    { title: '备注', dataIndex: 'notes', key: 'notes' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>详情</Button>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" icon={<DeleteOutlined />} danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({ ...pagination, current: 1 });
  };

  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({ ...pagination, current: 1 });
  };

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ marginBottom: 24 }}>
          <Form.Item name="store_id" label="门店">
            <Select placeholder="请选择门店" style={{ width: 150 }} allowClear>
              {stores && stores.map((store) => (
                <Option key={store.id} value={store.id}>
                  {store.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="cleaner_id" label="保洁员">
            <Select placeholder="请选择保洁员" style={{ width: 150 }} allowClear>
              {cleaners && cleaners.map((cleaner) => (
                <Option key={cleaner.id} value={cleaner.id}>
                  {cleaner.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 150 }} allowClear>
              <Option value={0}>待处理</Option>
              <Option value={1}>进行中</Option>
              <Option value={2}>已完成</Option>
              <Option value={3}>已取消</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>创建保洁记录</Button>
        </div>
        <Table
          columns={columns}
          dataSource={records}
          pagination={pagination}
          loading={loading}
          onChange={(p) => setPagination(p)}
          rowKey="id"
        />
      </Card>
      <Modal
        title="保洁记录详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
      >
        {currentRecord && (
          <div>
            <p><strong>门店名称:</strong> {stores.find(store => store.id === currentRecord.store_id)?.name || '未知门店'}</p>
            <p><strong>场地名称:</strong> {venues.find(venue => venue.id === currentRecord.venue_id)?.name || '未知场地'}</p>
            <p><strong>保洁员:</strong> {cleaners.find(cleaner => cleaner.id === currentRecord.cleaner_id)?.name || '未知保洁员'}</p>
            <p><strong>状态:</strong> <Tag color={statusMap[currentRecord.status]?.color}>{statusMap[currentRecord.status]?.text}</Tag></p>
            <p><strong>开始时间:</strong> {moment(currentRecord.start_time).format('YYYY-MM-DD HH:mm')}</p>
            <p><strong>结束时间:</strong> {moment(currentRecord.end_time).format('YYYY-MM-DD HH:mm')}</p>
            <p><strong>备注:</strong> {currentRecord.notes || '无'}</p>
          </div>
        )}
      </Modal>
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        onOk={handleFormSubmit}
        destroyOnClose
      >
        <Form form={recordForm} layout="vertical">
          <Form.Item label="门店" name="store_id" rules={[{ required: true, message: '请选择门店' }]}>
            <Select placeholder="请选择门店">
              {stores.map(store => (
                <Option key={store.id} value={store.id}>{store.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="场地" name="venue_id" rules={[{ required: true, message: '请选择场地' }]}>
            <Select placeholder="请选择场地">
              {venues.map(venue => (
                <Option key={venue.id} value={venue.id}>{venue.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="保洁员" name="cleaner_id" rules={[{ required: true, message: '请选择保洁员' }]}>
            <Select placeholder="请选择保洁员">
              {cleaners.map(cleaner => (
                <Option key={cleaner.id} value={cleaner.id}>{cleaner.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="开始时间" name="start_time" rules={[{ required: true, message: '请选择开始时间' }]}>
            <DatePicker showTime style={{ width: '100%' }} format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          <Form.Item label="结束时间" name="end_time">
            <DatePicker showTime style={{ width: '100%' }} format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
            <Select>
              <Option value={0}>待处理</Option>
              <Option value={1}>进行中</Option>
              <Option value={2}>已完成</Option>
              <Option value={3}>已取消</Option>
            </Select>
          </Form.Item>
          <Form.Item label="备注" name="notes">
            <Input.TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CleaningRecordList;